package interview.lock;

/**
 * 线程交替执行
 */
public class ThreadRotationExecute {
    private static Object lock1 = new Object();
    private boolean isPrint = true;
    public static void main(String[] args) {
        ThreadRotationExecute threadRotationExecute = new ThreadRotationExecute();
        Thread t1 = new Thread(threadRotationExecute.new MyThread1(lock1));
        Thread t2 = new Thread(threadRotationExecute.new MyThread2(lock1));
        t1.start();
        t2.start();
    }

    class MyThread1 implements Runnable{
        private Object object;
        public MyThread1(Object object) {
            this.object = object;
        }
        @Override
        public void run() {
            synchronized (object) {
            for (int i = 0; i < 100; i++) {
                if (isPrint) {
                    System.out.println(Thread.currentThread().getName());
                    isPrint = false;
                    object.notify();
                } else{
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            }
        }

    }
    class MyThread2 implements Runnable{
        private Object object;
        public MyThread2(Object object) {
            this.object = object;
        }
        @Override
        public void run() {
            synchronized (object) {
            for (int i = 0; i < 100; i++) {
                if (!isPrint) {
                    System.out.println(Thread.currentThread().getName());
                    isPrint=true;
                    object.notify();

                }else {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            }
        }
    }
}

